package platform.udp.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

import java.nio.charset.Charset;

public class MyServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception {
        String msg = datagramPacket.content().toString(Charset.forName("GBK"));
        System.out.println("UDP服务端收到消息"+msg);
        // 向客户端发送消息
        String json = "已收到";
        // 由于数据报的数据是字符串形式存储的，所以转数据
        byte[] bytes = json.getBytes(Charset.forName("GBK"));
        DatagramPacket datagramPacket1 = new DatagramPacket(Unpooled.copiedBuffer(bytes),datagramPacket.sender());
        channelHandlerContext.writeAndFlush(datagramPacket1);// 向客户端发送消息

    }
}
